package com.huatai.dataservice.fire.feign;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huatai.dataservice.domain.*;
import com.huatai.dataservice.fire.firemodel.*;
import com.huatai.dataservice.fire.service.*;
import com.huatai.dataservice.fire.service.impl.TbFireSafetyHazardRecordServiceImpl;
import com.huatai.dataservice.fire.service.impl.TbXfGenericPlanBServiceImpl;
import com.huatai.dataservice.fire.util.FireUtils;
import io.swagger.annotations.Api;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName FireWarningMonitoringController
 * @Description TODO
 * @Author gaowengui
 * @Date 2025/06/05 16:20:55
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("fire/feign")
@Api(tags = "消防验收接口", value = "消防验收接口")
public class FireWarningMonitoringController implements FireClient {

    @Autowired
    private TbFireSafetySituationService tbFireSafetySituationService;

    @Autowired
    private TbFireSafetyHazardRecordService tbFireSafetyHazardRecordService;

    @Autowired
    private TbFireAlarmRecordService tbFireAlarmRecordService;

    @Autowired
    private TbFireBrigadeStationCapacityService tbFireBrigadeStationCapacityService;

    @Autowired
    private TbFireWaterSourceSituationService tbFireWaterSourceSituationService;

    @Autowired
    private TbFireEvaluationRecordService tbFireEvaluationRecordService;

    @Autowired
    private TbFireWorkingPressureService tbFireWorkingPressureService;

    @Autowired
    private TbFireResponseSpeedService tbFireResponseSpeedService;

    @Autowired
    TbXfGenericPlanBService tbXfGenericPlanBService;

    @Autowired
    private TbXfGenericPlanBServiceImpl tbXfGenericPlanBServiceImpl;

    @Autowired
    private TbFireSafetyHazardRecordServiceImpl tbFireSafetyHazardRecordServiceImpl;

    /**
     * @return
     * @author gaowengui
     */
    @GetMapping("/selectFireSafetySituation")
    @Override
    public FireResponseVo selectFireSafetySituation() {
        List<TbFireSafetySituation> fireSafetySituationList = tbFireSafetySituationService.selectFireSafetySituation();
        List<Map<String, Object>> maps = new ArrayList<>();
        for (TbFireSafetySituation fireSafetySituation : fireSafetySituationList) {
            Map<String, Object> hashMap = new HashMap<>();
            String elecalarmcount = fireSafetySituation.getElecalarmcount();//用电隐患告警
            String hostalarmcount = fireSafetySituation.getHostalarmcount();//主机告警
            String wateralarmcount = fireSafetySituation.getWateralarmcount();//主机告警
            float fs = 100 - (Float.parseFloat(elecalarmcount) * 4) - Float.parseFloat(hostalarmcount) * 21 - Float.parseFloat(wateralarmcount) * 7;
            fireSafetySituation.setFS(fs);
            if (fs == 100) {
                fireSafetySituation.setYHDJ("安全");
            } else if (fs > 80 && fs <= 99) {
                fireSafetySituation.setYHDJ("轻度风险");
            } else if (fs > 60 && fs <= 79) {
                fireSafetySituation.setYHDJ("中等风险");
            } else if (fs <= 59) {
                fireSafetySituation.setYHDJ("严重风险");
            }
            hashMap.put("MC", fireSafetySituation.getMC());
            hashMap.put("SSQH", fireSafetySituation.getSSQH());
            hashMap.put("AQFZR", fireSafetySituation.getAQFZR());
            hashMap.put("PHONE", fireSafetySituation.getPHONE());
            hashMap.put("FS", fireSafetySituation.getFS());
            hashMap.put("YHDJ", fireSafetySituation.getYHDJ());
            hashMap.put("Data_ID", fireSafetySituation.getId());
            hashMap.put("MLng", fireSafetySituation.getMLng());
            hashMap.put("MLat", fireSafetySituation.getMLat());
            maps.add(hashMap);
        }
        return new FireResponseVo(maps, fireSafetySituationList.size(), "获取部位安全评估分析清单");
    }

    /**
     * 获取该重点部位的安全评分详情报告
     * * @author gaowengui
     *
     * @param id
     * @return
     */
    @GetMapping("/selectSafeListDetail")
    @Override
    public FireResponseVo selectSafeListDetail(@RequestParam("id") String id) {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        FireResponseVo fireResponseVo = tbFireSafetySituationService.selectFireSafetySituationById(id);
        return fireResponseVo;
    }

    /**
     * 获取隐患告警总览统计数据
     *
     * @return
     * @author gaowengui
     */
    @GetMapping("/getSafeAlarmOverall")
    @Override
    public FireResponseVo getSafeAlarmOverall() {
        FireResponseVo fireResponseVo = tbFireSafetySituationService.selectFireSafetySituationAll();
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * 获取隐患告警类别分布数据
     */
    @GetMapping("/getSafeAlarmByClass")
    @Override
    public ResponseVo selectSafeAlarmByClass() {
        int hostNum = 0;
        int electricNum = 0;
        int waterNum = 0;
        ResponseVo fireResponseVo = new ResponseVo();
        List<TbFireSafetyHazardRecord> list = tbFireSafetyHazardRecordService.list();
        List<Map<String, Object>> alarmList = new ArrayList<>();
        for (TbFireSafetyHazardRecord record : list) {
            String majorClass = record.getMajorclass();
            switch (majorClass) {
                case "用电隐患告警":
                    electricNum++;
                    break;
                case "主机告警":
                    hostNum++;
                    break;
                case "用水隐患告警":
                    waterNum++;
                    break;
            }
        }

// 主机告警条目
        if (hostNum > 0) {
            Map<String, Object> hostEntry = new HashMap<>();
            hostEntry.put("name", "主机告警");
            hostEntry.put("value", hostNum);
            alarmList.add(hostEntry);
        }

// 用电安全隐患条目（注意名称转换）
        if (electricNum > 0) {
            Map<String, Object> electricEntry = new HashMap<>();
            electricEntry.put("name", "用电安全隐患");  // 名称与示例保持一致
            electricEntry.put("value", electricNum);
            alarmList.add(electricEntry);
        }

// 用水隐患告警条目（按实际需求决定是否包含）
        if (waterNum > 0) {
            Map<String, Object> waterEntry = new HashMap<>();
            waterEntry.put("name", "用水隐患告警");
            waterEntry.put("value", waterNum);
            alarmList.add(waterEntry);
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("list", alarmList);
        fireResponseVo.setMethodName("隐患按类型分布");
        fireResponseVo.setData(resultMap);
        return fireResponseVo;
    }


    /**
     * @return
     * @author gaowengui
     * 获取隐患告警解决情况分布数据
     */
    @GetMapping("/getSafeAlarmSolve")
    @Override
    public ResponseVo getSafeAlarmOverallSolve() {
        ResponseVo fireResponseVo = new ResponseVo();
        List<TbFireSafetyHazardRecord> list = tbFireSafetyHazardRecordService.list();
        List<Map<String, Long>> alarmList = new ArrayList<>();
        long total = 0;
        long done = 0;
        for (TbFireSafetyHazardRecord record : list) {
            total++;
            if ("已解决".equals(record.getState()))
                done++;
        }
        Map<String, Long> totalAndDoneMap = new HashMap<>();
        totalAndDoneMap.put("total", total);
        totalAndDoneMap.put("done", done);
        alarmList.add(totalAndDoneMap);
        fireResponseVo.setData(alarmList);
        Map<String, List<Map<String, Long>>> map = new HashMap<>();
        map.put("list", alarmList);
        fireResponseVo.setData(map);
        fireResponseVo.setMethodName("隐患解决情况");
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowenngui
     * 获取所有隐患告警记录
     */
    @GetMapping("/getSafeAlarmLog")
    @Override
    public FireResponseVo getSafeAlarmLog() {
        FireResponseVo fireResponseVo = new FireResponseVo();
        List<TbFireSafetyHazardRecord> list = tbFireSafetyHazardRecordService.list();
        Map<String, Object> hashMap = new HashMap<>();
        //hashMap.put("count", list.size());
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (TbFireSafetyHazardRecord record : list) {
            Map<String, Object> hashMap1 = new HashMap<>();
            hashMap1.put("QTexts", record.getUnitname() + "发现1处" + record.getSubclass());
            hashMap1.put("dangerType", record.getMajorclass());
            hashMap1.put("MC", record.getUnitname());
            hashMap1.put("AlarmTime", record.getTime());
            hashMap1.put("FireDeptMC", record.getDistrictname());
            hashMap1.put("FireDuty", record.getCharger());
            hashMap1.put("FireDutyTel", FireUtils.phoneDesensitization(record.getContact()));

            mapList.add(hashMap1);
        }
        hashMap.put("list", mapList);
        fireResponseVo.setData(hashMap);
        fireResponseVo.setCount(list.size());
        fireResponseVo.setMethodName("查询所有隐患记录");
        return fireResponseVo;
    }

    /**
     * @param className
     * @return
     * @author gaowengui
     * 获取指定类型的隐患告警的区域分布
     */
    @GetMapping("/getSafeAlarmDistributionByClass")
    @Override
    public ResponseVo getSafeAlarmByClasss(String className) {
        List<TbFireSafetySituation> tbFireSafetySituationList = tbFireSafetySituationService.list();
        List<TbFireSafetyHazardRecord> tbFireSafetyHazardRecordList = null;
        if (className == null || className == "") {
            tbFireSafetyHazardRecordList = tbFireSafetyHazardRecordServiceImpl.selectAll();
        } else {
            tbFireSafetyHazardRecordList = tbFireSafetyHazardRecordService.selectByClassName(className);
        }
        ResponseVo fireResponseVo = new ResponseVo();
        List<Object> arrayList1 = new ArrayList<>();
        for (TbFireSafetySituation tbFireSafetySituation : tbFireSafetySituationList) {
            String districtname = tbFireSafetySituation.getSSQH();
            Map<String, Object> hashMap = new HashMap<>();
            List<Map<String, Object>> arrayList = new ArrayList<>();
            hashMap.put("SSQH", districtname);
            for (TbFireSafetyHazardRecord tbFireSafetyHazardRecord : tbFireSafetyHazardRecordList) {
                if (districtname.equals(tbFireSafetyHazardRecord.getDistrictname())) {
                    Map<String, Object> hashMap1 = new HashMap<>();
                    hashMap1.put("MC", tbFireSafetySituation.getMC());
                    hashMap1.put("AlarmType", tbFireSafetyHazardRecord.getSubclass());
                    hashMap1.put("AlarmTime", tbFireSafetyHazardRecord.getTime());
                    hashMap1.put("AQFZR", tbFireSafetySituation.getAQFZR());
                    hashMap1.put("PHONE", tbFireSafetySituation.getPHONE());
                    hashMap1.put("Data_ID", tbFireSafetySituation.getId());
                    arrayList.add(hashMap1);
                }
                hashMap.put("alarmList", arrayList);
            }
            arrayList1.add(hashMap);
        }
        fireResponseVo.setData(arrayList1);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_SAFE_ALARM_DISTRIBUTION_BY_CLASS);
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * 获取隐患巡察任务情况数据
     */
    @GetMapping("/getPatrol")
    @Override
    public FireResponseVo getPatrol() {
        FireResponseVo fireResponseVo = new FireResponseVo();
        List<TbFireSafetyHazardRecord> list = tbFireSafetyHazardRecordService.list();
        ArrayList<Map<String, Object>> listMap = new ArrayList<>();
        for (TbFireSafetyHazardRecord record : list) {
            Map<String, Object> hashMap = new HashMap<>();
            Map<String, Object> hashMap1 = new HashMap<>();
            List<Map<String, Object>> patrolList = new ArrayList<>();
            Map<String, Object> patrolListMap2 = new HashMap<>();
            hashMap.put("SSQH", record.getDistrictname());
            hashMap1.put("MC", record.getUnitname());
            hashMap1.put("time", record.getTime());
            hashMap1.put("user", record.getCharger());
            hashMap1.put("Data_ID", record.getId());
            patrolList.add(hashMap1);
            hashMap.put("patrolList", patrolList);
            listMap.add(hashMap);
        }
        fireResponseVo.setCount(list.size());
        fireResponseVo.setMethodName("获取巡察检查情况数据");
        fireResponseVo.setData(listMap);
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * 获取警情影响位置类型分布
     */
    @GetMapping("/getAlertByClass")
    @Override
    public ResponseVo getAlertByClass() {
        List<TbFireAlarmRecord> tbFireAlarmRecordList = tbFireAlarmRecordService.list();
        ResponseVo fireResponseVo = new ResponseVo();
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        for (TbFireAlarmRecord record : tbFireAlarmRecordList) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("typeName", record.getAreatype());
            hashMap.put("count", record.getFrequency());
            listMap.add(hashMap);
        }

        // 分组统计
        Map<PoliceTypeCountEnum, Long> rescueTypeCounts = tbFireAlarmRecordList.stream()
                .map(record -> PoliceTypeCountEnum.fromDisplayName(record.getAreatype())) // 转换类型
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                ));

        // 构建完整统计结果
        List<Map<String, Object>> chartData = Arrays.stream(PoliceTypeCountEnum.values())
                .map(type -> {
                    Map<String, Object> dataPoint = new HashMap<>();
                    dataPoint.put("typeName", type.getDisplayName());
                    dataPoint.put("count", rescueTypeCounts.getOrDefault(type, 0L));
                    return dataPoint;
                })
                .collect(Collectors.toList());
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_ALERT_BY_CLASS);
        fireResponseVo.setData(chartData);
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * 获取警情按时段分布数据
     */
    @GetMapping("/getAlertByPeriod")
    @Override
    public ResponseVo getAlertByPeriod() {
        //List<TbFireAlarmRecord> list = tbFireAlarmRecordService.list();
        List<Map<String, String>> listStr = tbFireAlarmRecordService.selectAllTbFireAlarmRecord();
        Map<TimePeriodEnum, Integer> periodCounts = new EnumMap<>(TimePeriodEnum.class);
        Map<String, List<Map<String, Object>>> stringListHashMap = new HashMap<>();

        // Initialize period counts
        for (TimePeriodEnum period : TimePeriodEnum.values()) {
            periodCounts.put(period, 0);
        }
        for (Map<String, String> recordMap : listStr) {
            String time = recordMap.get("time");
            log.info("==字符strtime=={}", time);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // Parse the string into LocalDateTime
            LocalDateTime localDateTime = LocalDateTime.parse(time, formatter);
            // Extract the hour
            int hour = localDateTime.getHour();
            log.info("===转为字符串时间==={}", hour);
            TimePeriodEnum period = TimePeriodEnum.getPeriod(hour);
            periodCounts.put(period, periodCounts.get(period) + 1);
        }

        List<Map<String, Object>> chartData = new ArrayList<>();
        for (TimePeriodEnum period : TimePeriodEnum.values()) {
            log.info("循环得到TimePeriodEnum枚举类的值:{}", period);
            Map<String, Object> dataPoint = new HashMap<>();
            dataPoint.put("periodName", period.getDisplayName());
            dataPoint.put("count", periodCounts.get(period));
            log.info("获取到的值：{}", periodCounts.get(period));
            chartData.add(dataPoint);
        }

        stringListHashMap.put("chart", chartData);
        ResponseVo response = new ResponseVo();
        response.setData(stringListHashMap);
        response.setMethodName(FireMonitoringWarningConstant.GET_ALERT_BY_PERIOD);
        return response;
    }

    /**
     * @return
     * @author gaowengui
     * 获取警情出动分类分布
     */
    @GetMapping("/getAlertByDispatch")
    @Override
    public ResponseVo getAlertByDispatch() {
        ResponseVo fireResponseVo = new ResponseVo();
        List<TbFireAlarmRecord> records = tbFireAlarmRecordService.list();
        if (records == null || records.isEmpty()) {
            return fireResponseVo;
        }
        // 分组统计
        Map<RescueTypeEnum, Long> rescueTypeCounts = records.stream()
                .map(record -> RescueTypeEnum.fromDisplayName(record.getType())) // 转换类型
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                ));

        // 构建完整统计结果
        List<Map<String, Object>> chartData = Arrays.stream(RescueTypeEnum.values())
                .map(type -> {
                    Map<String, Object> dataPoint = new HashMap<>();
                    dataPoint.put("name", type.getDisplayName());
                    dataPoint.put("count", rescueTypeCounts.getOrDefault(type, 0L));
                    return dataPoint;
                })
                .collect(Collectors.toList());

        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_ALERT_BY_DISPATCH);
        fireResponseVo.setData(chartData);
        return fireResponseVo;
    }


    @GetMapping("/getAlertByAcception")
    @Override
    public FireResponseVo getAlertByAcception() {
        FireResponseVo fireResponseVo = new FireResponseVo();
        List<TbFireAlarmRecord> records = tbFireAlarmRecordService.list();
        if (records == null || records.isEmpty()) {
            return fireResponseVo;
        }

        Map<AlarmDistributionEnum, Long> AlarmDistributionEnumCounts = records.stream()
                .map(record -> AlarmDistributionEnum.fromDisplayName(record.getAcceptedteam()))
                .collect(Collectors.groupingBy(
                        Function.identity(),
                        Collectors.counting()
                ));

        List<Map<String, Object>> chartData = Arrays.stream(AlarmDistributionEnum.values())
                .map(type -> {
                    Map<String, Object> dataPoint = new HashMap<>();
                    dataPoint.put("unitName", type.getDisplayName());
                    dataPoint.put("count", AlarmDistributionEnumCounts.getOrDefault(type, 0L));
                    return dataPoint;
                })
                .collect(Collectors.toList());

        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("chart", chartData);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_ALERT_BY_ACCEPTION);
        fireResponseVo.setData(hashMap);
        fireResponseVo.setCount(records.size());
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * 获取队站情况数据
     */
    @GetMapping("/getTeamStaff")
    @Override
    public ResponseVo getTeamStaff() {
        List<TbFireBrigadeStationCapacity> list = tbFireBrigadeStationCapacityService.selectAll();
        ResponseVo fireResponseVo = new ResponseVo();
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        if (list == null || list.isEmpty()) {
            return fireResponseVo;
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (TbFireBrigadeStationCapacity capacity : list) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("teamName", capacity.getName());
            hashMap.put("count", capacity.getStaff());
            mapList.add(hashMap);
        }
        map.put("chart", mapList);
        fireResponseVo.setData(map);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_TEAM_STAFF);
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * 获取执勤车辆统计数据
     */
    @GetMapping("/getVehicleByTeam")
    @Override
    public ResponseVo getVehicleByTeam() {
        ResponseVo fireResponseVo = new ResponseVo();
        List<TbFireBrigadeStationCapacity> tbFireBrigadeStationCapacityList = tbFireBrigadeStationCapacityService.selectAll();
        if (tbFireBrigadeStationCapacityList == null || tbFireBrigadeStationCapacityList.isEmpty()) {
            return fireResponseVo;
        }
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        for (TbFireBrigadeStationCapacity capacity : tbFireBrigadeStationCapacityList) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("teamName", capacity.getName());
            hashMap.put("count", capacity.getZqvehicle());
            list.add(hashMap);
        }
        map.put("chart", list);
        fireResponseVo.setData(map);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_VEHICLE_BY_TEAM);
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * 获取消防车类型数据
     */
    @GetMapping("/getXFCarByType")
    @Override
    public ResponseVo getXFCarByType() {
        ResponseVo fireResponseVo = new ResponseVo();
        List<TbFireBrigadeStationCapacity> tbFireBrigadeStationCapacityList = tbFireBrigadeStationCapacityService.selectAll();
        if (tbFireBrigadeStationCapacityList == null || tbFireBrigadeStationCapacityList.isEmpty()) {
            return fireResponseVo;
        }
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();

        int[] sums = new int[3]; // sums[0]=tqxf, sums[1]=mh, sums[2]=jg

        tbFireBrigadeStationCapacityList.forEach(record -> {
            // 特勤消防车
            if (record.getTqxfvehicle() != null) {
                sums[0] += record.getTqxfvehicle();
            }
            // 灭火消防车
            if (record.getMhvehicle() != null) {
                sums[1] += record.getMhvehicle();
            }
            // 举高消防车
            if (record.getJgvehicle() != null) {
                sums[2] += record.getJgvehicle();
            }
        });

        int tqxfvehicle = sums[0];
        int mhVehicle = sums[1];
        int jgVehicle = sums[2];


        List<Map<String, Object>> chartData = Arrays.asList(
                createCarMap("灭火消防车", mhVehicle),
                createCarMap("举高消防车", jgVehicle),
                createCarMap("特勤消防车", tqxfvehicle)
        );
        map.put("chart", chartData);
        fireResponseVo.setData(map);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_XF_CAR_BY_TYPE);
        return fireResponseVo;
    }


    /**
     * @param carType
     * @param count
     * @return
     * @author gaowengui
     * 获取消防车类型map集合
     */
    private Map<String, Object> createCarMap(String carType, int count) {
        return new HashMap<String, Object>() {{
            put("carType", carType);
            put("count", count);
        }};
    }

    /**
     * @return
     * @author gaowengui
     * 获取预案编制进度情况
     */
    @GetMapping("/getResProgress")
    @Override
    public ResponseVo getResProgress() {
        ResponseVo fireResponseVo = new ResponseVo();
        List<TbFireBrigadeStationCapacity> tbFireBrigadeStationCapacityList = tbFireBrigadeStationCapacityService.selectAll();
        if (tbFireBrigadeStationCapacityList == null || tbFireBrigadeStationCapacityList.isEmpty()) {
            return fireResponseVo;
        }
        Map<Object, List<Map<String, Object>>> map = new HashMap<>();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (TbFireBrigadeStationCapacity capacity : tbFireBrigadeStationCapacityList) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("teamName", capacity.getName());
            if (capacity.getRequire() != null && capacity.getRequire().intValue() != 0) {
                double progress = (double) capacity.getFinished() / capacity.getRequire();
                BigDecimal bd = new BigDecimal(progress * 100).setScale(1, RoundingMode.HALF_UP);
                hashMap.put("progress", bd);
            } else {
                hashMap.put("progress", 0.0d);
            }
            mapList.add(hashMap);
        }
        map.put("chart", mapList);
        fireResponseVo.setData(map);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_RES_PROGRESS);
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * 获取水源情况
     */
    @GetMapping("/getWaterProgress")
    @Override
    public ResponseVo getWaterProgress() {
        ResponseVo fireResponseVo = new ResponseVo();
        List<TbFireWaterSourceSituation> list = tbFireWaterSourceSituationService.list();
        if (list == null || list.isEmpty()) {
            return fireResponseVo;
        }
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        List<Map<String, Object>> arrayList = new ArrayList<>();
        for (TbFireWaterSourceSituation situation : list) {
            Map<String, Object> hashMap = new HashMap<>();
            hashMap.put("name", situation.getName());
            hashMap.put("normal", situation.getAvailable());
            hashMap.put("abnormal", situation.getUnavailable());
            arrayList.add(hashMap);
        }
        map.put("chart", arrayList);
        fireResponseVo.setData(map);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_WATER_PROGRESS);
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * @describe 获取个人效能指数
     */
    @GetMapping("/getEffIndexByName")
    @Override
    public ResponseVo getEffIndexByName(@RequestParam("name") String name, @RequestParam("dep") String dep) {
        ResponseVo fireResponseVo = new ResponseVo();
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_EFF_INDEX_BY_NAME);
        if ((name == null || name.isEmpty()) || (dep == null || dep.isEmpty())) {
            fireResponseVo.setData("name,dep参数不能为空");
            return fireResponseVo;
        }
        //考核记录表
        LambdaQueryWrapper<TbFireEvaluationRecord> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(TbFireEvaluationRecord::getName, name).eq(TbFireEvaluationRecord::getDep, dep);
        List<TbFireEvaluationRecord> list = tbFireEvaluationRecordService.selectByNameAndDep(lambdaQueryWrapper);
        //工作压力数据
        LambdaQueryWrapper<TbFireWorkingPressure> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.eq(TbFireWorkingPressure::getHandlerdep, dep);
        List<TbFireWorkingPressure> tbFireWorkingPressureListDep = tbFireWorkingPressureService.selectAllDep(objectLambdaQueryWrapper);
        LambdaQueryWrapper<TbFireWorkingPressure> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(TbFireWorkingPressure::getHandler, name).eq(TbFireWorkingPressure::getHandlerdep, dep);
        List<TbFireWorkingPressure> listWorkPressure = tbFireWorkingPressureService.selectByNameAndDep(lambdaQuery);
        //响应速度
        LambdaQueryWrapper<TbFireResponseSpeed> lambdaQueryWrapper1 = Wrappers.lambdaQuery();
        lambdaQueryWrapper1.eq(TbFireResponseSpeed::getHandler, name).eq(TbFireResponseSpeed::getHandlerdep, dep);
        List<TbFireResponseSpeed> responseSpeedsList = tbFireResponseSpeedService.selectByNameAndDep(lambdaQueryWrapper1);
        if (list == null || list.isEmpty()) {
            return fireResponseVo;
        }
        List<Map<String, Object>> examList = new ArrayList<>();
        TbFireEvaluationRecord tbFireEvaluationRecord = list.get(0);
        double redGrade = 0;
        double depResult = 0;
        double amountResult = 0;
        for (TbFireEvaluationRecord tbFireEvaluationRecords : list) {
            String title = tbFireEvaluationRecords.getType();
            if ("红门政教".equals(title)) {
                redGrade = tbFireEvaluationRecords.getScore();//
            }
            if ("干部绩效考评".equals(title)) {
                depResult = tbFireEvaluationRecords.getScore();
            }
            if ("队管云量化考评".equals(title)) {
                amountResult = tbFireEvaluationRecords.getScore();
            }
        }
        //获取业务能力指数
        double capacityScore = FireUtils.businessCapability(redGrade, depResult, amountResult);
        //工作压力指数
        double pressureScore = FireUtils.workPressure(listWorkPressure.size(), tbFireWorkingPressureListDep.size());
        //响应速度指数
        int size = responseSpeedsList.size();//总事项
        int anshi = 0;
        for (TbFireResponseSpeed tbFireResponseSpeed : responseSpeedsList) {
            if (tbFireResponseSpeed.getActualfinishtime().before(tbFireResponseSpeed.getRequiredfinishtime()))
                anshi++;
        }
        double responseScore = FireUtils.workPressure(anshi, size);

        //效能指数
        double score = FireUtils.personalEffectiveness(capacityScore, pressureScore, responseScore, redGrade, depResult, amountResult);
        Map<String, Object> map = new HashMap<>();
        map.put("userName", tbFireEvaluationRecord.getName());
        map.put("groupName", tbFireEvaluationRecord.getDep());
        map.put("redGradeRemark", "红门政教");
        map.put("redGrade", redGrade);
        map.put("depResultRemark", "干部绩效");
        map.put("depResult", depResult);
        map.put("amountResultRemark", "队管云量化");
        map.put("amountResult", amountResult);
        map.put("score", score);
        map.put("capacityScore", capacityScore);
        for (TbFireEvaluationRecord tbFireEvaluationRecord1 : list) {
            Map<String, Object> examMap = FireUtils.createExamMap(tbFireEvaluationRecord1.getTitle(), tbFireEvaluationRecord1.getName(), tbFireEvaluationRecord1.getTime(), tbFireEvaluationRecord1.getScore());
            examList.add(examMap);
        }
        map.put("examList", examList);

        map.put("pressureScore", pressureScore);//
        List<Map<String, Object>> pressureList = new ArrayList<>();
        for (TbFireWorkingPressure tbFireWorkingPressure : listWorkPressure) {
            Map<String, Object> map1 = FireUtils.pressureList(tbFireWorkingPressure.getTitle(), tbFireWorkingPressure.getActualfinishtime());
            pressureList.add(map1);
        }
        map.put("pressureList", pressureList);
        map.put("responseScore", responseScore);
        map.put("responseOnTime", anshi);
        map.put("responseOutTime", size - anshi);

        List<Map<String, Object>> responseList = new ArrayList<>();
        for (TbFireResponseSpeed tbFireResponseSpeed : responseSpeedsList) {
            Map<String, Object> map1 = FireUtils.responseMap(tbFireResponseSpeed.getType(), tbFireResponseSpeed.getRequiredfinishtime(), tbFireResponseSpeed.getActualfinishtime());
            responseList.add(map1);
        }
        map.put("responseList", responseList);
        fireResponseVo.setData(map);

        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * @describe 获取业务能力指数分布情况
     */
    @GetMapping("/getCapacityIndexByLevel")
    @Override
    public ResponseVo getCapacityIndexByLevel() {
        List<TbFireEvaluationRecord> list = tbFireEvaluationRecordService.list();
        ResponseVo fireResponseVo = new ResponseVo();
        if (list == null || list.isEmpty()) return fireResponseVo;
        Map<String, List<TbFireEvaluationRecord>> collect = list.stream().collect(Collectors.groupingBy(TbFireEvaluationRecord::getName));
        Iterator<Map.Entry<String, List<TbFireEvaluationRecord>>> iterator = collect.entrySet().iterator();
        int value1 = 0;
        int value2 = 0;
        int value3 = 0;
        int value4 = 0;
        int value5 = 0;
        while (iterator.hasNext()) {
            Map.Entry<String, List<TbFireEvaluationRecord>> entry = iterator.next();
            String key = entry.getKey();
            List<TbFireEvaluationRecord> list1 = entry.getValue();
            double redGrade = 0;
            double depResult = 0;
            double amountResult = 0;
            for (TbFireEvaluationRecord tbFireEvaluationRecord : list1) {
                String title = tbFireEvaluationRecord.getType();
                if (FireMonitoringWarningConstant.HONG_MEN_ZHENGJIAO.equals(title)) {//红门政教
                    redGrade = tbFireEvaluationRecord.getScore();
                } else if (FireMonitoringWarningConstant.GAN_BU_JI_XIAO.equals(title)) {//干部绩效
                    depResult = tbFireEvaluationRecord.getScore();
                } else if (FireMonitoringWarningConstant.DUI_GUAN_YUN_LAINGHUA.equals(title)) {//对管量化云
                    amountResult = tbFireEvaluationRecord.getScore();
                }
            }
            double v = FireUtils.businessCapability(redGrade, depResult, amountResult);
            if (0 <= v && v < 20) {
                value1++;
            } else if (20 <= v && v < 40) {
                value2++;
            } else if (40 <= v && v < 60) {
                value3++;
            } else if (60 <= v && v < 80) {
                value4++;
            } else if (80 <= v && v < 100) {
                value5++;
            }
        }


        Map<String, Object> hashMap1 = new HashMap<>();
        Map<String, Object> hashMap2 = new HashMap<>();
        Map<String, Object> hashMap3 = new HashMap<>();
        Map<String, Object> hashMap4 = new HashMap<>();
        Map<String, Object> hashMap5 = new HashMap<>();
        hashMap1.put("name", "0-20分");
        hashMap1.put("value", value1);
        hashMap2.put("name", "20-40分");
        hashMap2.put("value", value2);
        hashMap3.put("name", "40-60分");
        hashMap3.put("value", value3);
        hashMap4.put("name", "60-80分");
        hashMap4.put("value", value4);
        hashMap5.put("name", "80-100分");
        hashMap5.put("value", value5);
        List<Map<String, Object>> arrayList = new ArrayList<>();
        arrayList.add(hashMap1);
        arrayList.add(hashMap2);
        arrayList.add(hashMap3);
        arrayList.add(hashMap4);
        arrayList.add(hashMap5);
        Map<String, List<Map<String, Object>>> hashMap = new HashMap<>();
        hashMap.put("chart", arrayList);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_CAPACITY_INDEX_BY_LEVEL);
        fireResponseVo.setData(hashMap);
        return fireResponseVo;
    }

    /**
     * @return
     * @describe 获取部门效能指数
     */
    @GetMapping("/getDeptIndexByName")
    @Override
    public ResponseVo getDeptIndexByName() {
        ResponseVo fireResponseVo = new ResponseVo();
        List<TbFireBrigadeStationCapacity> xfStaffList = tbFireBrigadeStationCapacityService.selectAll();
        List<Map<String, Object>> maps = new ArrayList<>();
        //考核记录表
        List<TbFireEvaluationRecord> list = tbFireEvaluationRecordService.list();
        Map<String, List<TbFireEvaluationRecord>> collect = list.stream().collect(Collectors.groupingBy(TbFireEvaluationRecord::getDep));
        Map<String, Map<String, List<TbFireEvaluationRecord>>> recordByname = collect.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey, // 保留第一次分组的键（dep）
                        entry -> entry.getValue().stream()
                                .collect(Collectors.groupingBy(TbFireEvaluationRecord::getName)) // 根据 name 字段分组
                ));
        //工作压力数据
        List<TbFireWorkingPressure> listWorkPressure = tbFireWorkingPressureService.list();
        Map<String, List<TbFireWorkingPressure>> collect1 = listWorkPressure.stream().collect(Collectors.groupingBy(TbFireWorkingPressure::getHandlerdep));
        Map<String, Map<String, List<TbFireWorkingPressure>>> pressureByname = collect1.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .collect(Collectors.groupingBy(TbFireWorkingPressure::getHandler))
                ));
        //响应速度
        List<TbFireResponseSpeed> responseSpeedsList = tbFireResponseSpeedService.list();
        Map<String, List<TbFireResponseSpeed>> collect2 = responseSpeedsList.stream().collect(Collectors.groupingBy(TbFireResponseSpeed::getHandlerdep));
        Map<String, Map<String, List<TbFireResponseSpeed>>> responseByname = collect2.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().stream()
                                .collect(Collectors.groupingBy(TbFireResponseSpeed::getHandler))
                ));


        for (TbFireBrigadeStationCapacity tbFireBrigadeStationCapacity : xfStaffList) {//消防队伍、部门
            Integer staff = tbFireBrigadeStationCapacity.getStaff();//获取每个消防部门的人数
            String deptName = tbFireBrigadeStationCapacity.getName();//部门名称
            Map<String, Object> hashMap1 = new HashMap<>();
            hashMap1.put("depName", deptName);
            double score = 0;
            hashMap1.put("score",score);
            Iterator<Map.Entry<String, Map<String, List<TbFireEvaluationRecord>>>> recordIter = recordByname.entrySet().iterator();
            while (recordIter.hasNext()) {

                Map.Entry<String, Map<String, List<TbFireEvaluationRecord>>> next = recordIter.next();
                String dept = next.getKey();//部门
                if (deptName.equals(dept)) {
                    Map<String, List<TbFireEvaluationRecord>> value = next.getValue();
                    Iterator<Map.Entry<String, List<TbFireEvaluationRecord>>> iterator = value.entrySet().iterator();
                    ArrayList<Double> doubles = new ArrayList<>();
                    while (iterator.hasNext()) {
                        double redGrade = 0;
                        double depResult = 0;
                        double amountResult = 0;
                        Map.Entry<String, List<TbFireEvaluationRecord>> next1 = iterator.next();
                        String name = next1.getKey();//人名
                        List<TbFireEvaluationRecord> value1 = next1.getValue();
                        for (TbFireEvaluationRecord tbFireEvaluationRecords : value1) {
                            String title = tbFireEvaluationRecords.getType();
                            if ("红门政教".equals(title)) {
                                redGrade = tbFireEvaluationRecords.getScore();//
                            }
                            if ("干部绩效考评".equals(title)) {
                                depResult = tbFireEvaluationRecords.getScore();
                            }
                            if ("队管云量化考评".equals(title)) {
                                amountResult = tbFireEvaluationRecords.getScore();
                            }
                        }
                        //获取业务能力指数
                        double capacityScore = FireUtils.businessCapability(redGrade, depResult, amountResult);
                        Map<String, List<TbFireWorkingPressure>> pressureListMap = pressureByname.get(dept);
                        List<TbFireWorkingPressure> tbFireWorkingPressureList = pressureListMap.get(name);
                        //工作压力指数
                        double pressureScore = FireUtils.workPressure(tbFireWorkingPressureList.size(), pressureListMap.size());
                        //响应速度
                        Map<String, List<TbFireResponseSpeed>> stringListMap = responseByname.get(dept);
                        List<TbFireResponseSpeed> responseSpeeds = stringListMap.get(name);

                        //响应速度指数
                        int size = responseSpeeds.size();//总事项
                        int anshi = 0;
                        for (TbFireResponseSpeed tbFireResponseSpeed : responseSpeeds) {
                            if (tbFireResponseSpeed.getActualfinishtime().before(tbFireResponseSpeed.getRequiredfinishtime()))
                                anshi++;
                        }
                        double responseScore = FireUtils.workPressure(anshi, size);
                        //效能指数
                         score =score  + FireUtils.personalEffectiveness(capacityScore, pressureScore, responseScore, redGrade, depResult, amountResult);
                    }
                    //hashMap1.put("depName", dept);
                    hashMap1.put("score", FireUtils.calculateRatio(score,staff));
                }
            }
            maps.add(hashMap1);
        }
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("chart", maps);
        fireResponseVo.setData(hashMap);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_DEPT_INDEX_BY_NAME);
        return fireResponseVo;
    }


    /**
     * @return
     * @describe 获取工作压力指数分布情况
     */
    @GetMapping("/getPressureIndexByDep")
    @Override
    public ResponseVo getPressureIndexByDep() {
        List<TbFireWorkingPressure> list = tbFireWorkingPressureService.list();
        ResponseVo fireResponseVo = new ResponseVo();
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, List<TbFireWorkingPressure>> collect = list.stream()
                .collect(Collectors.groupingBy(TbFireWorkingPressure::getHandlerdep));

        Map<String, Map<String, List<TbFireWorkingPressure>>> multiLevelGrouping = collect.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,  // 保持一级分组键（handlerDep）
                        entry -> entry.getValue().stream()
                                .collect(Collectors.groupingBy(TbFireWorkingPressure::getHandler))  // 二级分组
                ));
        Map<String, Set<String>> uniqueHandlersByDep = list.stream()
                .collect(Collectors.groupingBy(
                        TbFireWorkingPressure::getHandlerdep,
                        Collectors.mapping(
                                TbFireWorkingPressure::getHandler,
                                Collectors.toSet()  // 自动去重
                        )
                ));
        Set<Map.Entry<String, Map<String, List<TbFireWorkingPressure>>>> entries1 = multiLevelGrouping.entrySet();
        Iterator<Map.Entry<String, Map<String, List<TbFireWorkingPressure>>>> iterator1 = entries1.iterator();
        Set<Map.Entry<String, List<TbFireWorkingPressure>>> entries = collect.entrySet();
        Iterator<Map.Entry<String, List<TbFireWorkingPressure>>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<TbFireWorkingPressure>> entry = iterator.next();
            String key = entry.getKey();
            Map<String, Object> hashMap = new HashMap<>();
            double source = 0;
            List<TbFireWorkingPressure> value = entry.getValue();
            int size = value.size();//每组有都少任务
            Map<String, List<TbFireWorkingPressure>> stringListMap = multiLevelGrouping.get(key);
            Set<Map.Entry<String, List<TbFireWorkingPressure>>> entries2 = stringListMap.entrySet();
            Iterator<Map.Entry<String, List<TbFireWorkingPressure>>> iterator2 = entries2.iterator();
            while (iterator2.hasNext()) {
                Map.Entry<String, List<TbFireWorkingPressure>> entry2 = iterator2.next();
                String key1 = entry2.getKey();
                List<TbFireWorkingPressure> value1 = entry2.getValue();
                int size1 = value1.size();//获取每组中每个人的任务数
                double v = FireUtils.workPressure(size1, size);//工作压力指数计算
                source = source + v;
                System.out.println("v = " + v);
                hashMap.put("depName", key);
                hashMap.put("score", v);
                mapList.add(hashMap);
            }
        }

//		List<Map<String,Object>> arrayList = new ArrayList<>();
//		for (DeptWorkPressureEnum deptWorkPressureEnum : DeptWorkPressureEnum.values()) {
//			Map<String, Object> hashMap = new HashMap<>();
//			String displayName = deptWorkPressureEnum.getDisplayName();
//			double value = deptWorkPressureEnum.getValue();
//			for (Map<String, Object> map : mapList) {
//				String depName = map.get("depName").toString();
//				double score = (double) map.get("score");
//				if (displayName.equals(depName)) {
//					hashMap.put("depName", depName);
//					hashMap.put("score", score);
//					arrayList.add(hashMap);
//					break;
//				}else {
//					hashMap.put("depName", displayName);
//					hashMap.put("score", value);
//					arrayList.add(hashMap);
//				}
//			}
//		}
        // 预处理mapList为Map结构
        Map<String, Double> scoreMap = mapList.stream()
                .collect(Collectors.toMap(
                        m -> (String) m.get("depName"),
                        m -> ((Number) m.get("score")).doubleValue()
                ));

        List<Map<String, Object>> arrayList = Arrays.stream(DeptWorkPressureEnum.values())
                .map(deptEnum -> {
                    Map<String, Object> resultMap = new HashMap<>();
                    resultMap.put("depName", deptEnum.getDisplayName());
                    resultMap.put("score", scoreMap.getOrDefault(
                            deptEnum.getDisplayName(),
                            deptEnum.getValue()
                    ));
                    return resultMap;
                })
                .collect(Collectors.toList());


        Map<String, List<Map<String, Object>>> hashMap = new HashMap<>();
        hashMap.put("chart", arrayList);
        fireResponseVo.setData(hashMap);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_PRESSURE_INDEX_BY_DEP);

        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * 获取响应速度指数分布情况
     */
    @GetMapping("/getResponseIndexByDep")
    @Override
    public ResponseVo getResponseIndexByDep() {
        List<TbFireResponseSpeed> list = tbFireResponseSpeedService.list();
        ResponseVo fireResponseVo = new ResponseVo();
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> arrayList = new ArrayList<>();
        int value1 = 0;
        int value2 = 0;
        int value3 = 0;
        int value4 = 0;
        int value5 = 0;
        Map<String, List<TbFireResponseSpeed>> tbFireResponseSpeedMap = list.stream()
                .collect(Collectors.groupingBy(TbFireResponseSpeed::getHandler));//总事项

        Iterator<Map.Entry<String, List<TbFireResponseSpeed>>> iterator1 = tbFireResponseSpeedMap.entrySet().iterator();
        while (iterator1.hasNext()){
            Map.Entry<String, List<TbFireResponseSpeed>> next = iterator1.next();//
            String key = next.getKey();
            List<TbFireResponseSpeed> tbFireResponseSpeedList = next.getValue();//获取个人总数据
            int ansiNum = 0;
            for (TbFireResponseSpeed tbFireResponseSpeed : tbFireResponseSpeedList) {
                Date actualfinishtime = tbFireResponseSpeed.getActualfinishtime();//获取实际完成时间
                Date requiredfinishtime = tbFireResponseSpeed.getRequiredfinishtime();//获取要求完成时间
                if (actualfinishtime.before(requiredfinishtime)) {
                    ansiNum++;
                }
            }
            //获取响应指数
            double v = FireUtils.workPressure(ansiNum, tbFireResponseSpeedList.size());
            if (v > 90 && v <= 100) {
                value1++;
            } else if (v > 80 && v <= 89) {
                value2++;
            } else if (v > 60 && v <= 79) {
                value3++;
            } else if (v > 40 && v <= 59) {
                value4++;
            } else if (v <= 39) {
                value5++;

            }
        }

        List<Map<String, Object>> chartData = Arrays.asList(
                FireUtils.createCarMaps("优秀", value1),
                FireUtils.createCarMaps("良好", value2),
                FireUtils.createCarMaps("中等", value3),
                FireUtils.createCarMaps("较差", value4),
                FireUtils.createCarMaps("差", value5)
        );
        Map<String, List<Map<String, Object>>> hashMap = new HashMap<>();
        hashMap.put("chart", chartData);
        fireResponseVo.setData(hashMap);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_RESPONSE_INDEX_BY_DEP);
        return fireResponseVo;
    }

    /**
     * 获取时效性风险情况
     *
     * @return
     */
    @GetMapping("/getRiskOfResponse")
    @Override
    public ResponseVo getRiskOfResponse() {
        List<TbFireResponseSpeed> list = tbFireResponseSpeedService.list();
        ResponseVo fireResponseVo = new ResponseVo();

        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        int value1 = 0;
        int value2 = 0;
        int value3 = 0;
        List<Map<String, Object>> maps = new ArrayList<>();
        for (TbFireResponseSpeed item : list) {
            Map<String, Object> hashMap1 = new HashMap<>();
            Date actualfinishtime = item.getActualfinishtime();//实际完成时间
            Date requiredfinishtime = item.getRequiredfinishtime();//要求完成时间
            double v = FireUtils.calculateHourDifference(actualfinishtime, requiredfinishtime);
            if (v > 0 && v < 24) {
                value1++;
            } else if (v > 24 && v <= 7 * 24) {
                value2++;
            } else if (v > 7 * 24) {
                value3++;
            }
            if (actualfinishtime.after(requiredfinishtime)) {
                hashMap1.put("Name", item.getType());
                hashMap1.put("TypeName", item.getType());
                hashMap1.put("TaskStartTime", FireUtils.dateTimeFormate(item.getBegintime()));
                hashMap1.put("TaskEndTime", FireUtils.dateTimeFormate(actualfinishtime));
                hashMap1.put("signTime", FireUtils.dateTimeFormate(item.getRequiredfinishtime()));
                hashMap1.put("TaskUserName", item.getHandler());
                hashMap1.put("isPassTime", "逾期");
                hashMap1.put("TaskOrganizationName", item.getHandlerdep());
                maps.add(hashMap1);
            }
        }

        List<Map<String, Object>> chartData = Arrays.asList(
                FireUtils.beOverdue("当日逾期", value1),
                FireUtils.beOverdue("逾期一周内", value2),
                FireUtils.beOverdue("逾期超一周", value3)
        );
        Map<String, Object> hashMap = new HashMap<>();
        int flishOnTime = list.size() - value1 - value2 - value3;//按时完成
        hashMap.put("flishOnTime", flishOnTime);
        hashMap.put("sumNum", list.size());

        hashMap.put("chart", chartData);
        hashMap.put("DataList", maps);
        fireResponseVo.setData(hashMap);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_RISK_OF_RESPONSE);
        return fireResponseVo;
    }

    /**
     * @return
     * @author gaowengui
     * 获取合规性风险情况
     */
    @GetMapping("/getRiskOfLegal")
    @Override
    public ResponseVo getRiskOfLegal() {
        List<TbFireResponseSpeed> list = tbFireResponseSpeedService.list();
        ResponseVo fireResponseVo = new ResponseVo();
        HashMap<String, Object> hashMap = new HashMap<>();
        int legalCount = list.size();//事项总数
        int illegalCount = 0;//不合规事项数
        ArrayList<Map<String, Object>> arrayList = new ArrayList<>();
        for (TbFireResponseSpeed tbFireResponseSpeed : list) {
            HashMap<String, Object> hashMap1 = new HashMap<>();
            Date actualfinishtime = tbFireResponseSpeed.getActualfinishtime();//实际完成时间
            Date requiredfinishtime = tbFireResponseSpeed.getRequiredfinishtime();//要求完成时间
            if (actualfinishtime.after(requiredfinishtime)) {//超时
                illegalCount++;
                hashMap1.put("id", tbFireResponseSpeed.getId());
                hashMap1.put("cause", FireMonitoringWarningConstant.TIME_OUT);
                hashMap1.put("roleName", tbFireResponseSpeed.getHandler());
                hashMap1.put("department", tbFireResponseSpeed.getHandlerdep());
                hashMap1.put("processState", FireMonitoringWarningConstant.NOT_SOLVE);
                hashMap1.put("createTime", FireUtils.dateTimeFormate(actualfinishtime));
                arrayList.add(hashMap1);
            }
        }
        hashMap.put("legalCount", legalCount - illegalCount);
        hashMap.put("illegalCount", illegalCount);
        hashMap.put("list", arrayList);
        fireResponseVo.setData(hashMap);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_RISK_OF_LEGAL);
        return fireResponseVo;
    }


    /**
     * @return
     * @author gaowengui
     * 获取风险评分
     */
    @GetMapping("/getRiskScore")
    @Override
    public ResponseVo getRiskScore() {
        List<TbFireResponseSpeed> list = tbFireResponseSpeedService.list();
        ResponseVo fireResponseVo = new ResponseVo();
        Map<String, Object> hashMap = new HashMap<>();
        int abnormalCount = 0;//异常数据
        int responseCount = 0;//超时事项数
        int legalCount = 0;//不合规事项数
        for (TbFireResponseSpeed tbFireResponseSpeed : list) {
            Date actualfinishtime = tbFireResponseSpeed.getActualfinishtime();//实际完成时间
            Date requiredfinishtime = tbFireResponseSpeed.getRequiredfinishtime();//要求完成时间
            if (actualfinishtime.after(requiredfinishtime)) {
                abnormalCount++;
                responseCount++;
                legalCount++;
            }
        }
        int abnormalCountScore = FireUtils.abnormalRiskScore(abnormalCount);
        int responseCountScore = FireUtils.outTimeRiskScore(responseCount);
        int legalCountScore = FireUtils.complianceRisk(legalCount);
        double v = FireUtils.riskScore(abnormalCountScore, responseCountScore, legalCountScore);
        hashMap.put("riskScore", v);
        hashMap.put("abnormalCount", abnormalCount);
        hashMap.put("abnormalScore", abnormalCountScore);
        hashMap.put("responseCount", responseCount);
        hashMap.put("responseScore", responseCountScore);
        hashMap.put("legalCount", legalCount);
        hashMap.put("legalScore", legalCountScore);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_RISK_SCORE);
        fireResponseVo.setData(hashMap);
        return fireResponseVo;
    }


    /**
     * 获取问题台帐
     *
     * @return
     */
    @GetMapping("/getProblems")
    @Override
    public ResponseVo getProblems() {
        List<TbFireResponseSpeed> responseList = tbFireResponseSpeedService.list();//响应
        ResponseVo fireResponseVo = new ResponseVo();
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        List<TbFireSafetyHazardRecord> safetyList = tbFireSafetyHazardRecordService.list();//安全隐患
        List<Map<String, Object>> maps1 = new ArrayList<>();
        for (TbFireSafetyHazardRecord tbFireSafetyHazardRecord : safetyList) {
            Map<String, Object> hashMap = new HashMap<>();
            String name = FireUtils.getName(tbFireSafetyHazardRecord.getUnitname(), tbFireSafetyHazardRecord.getGivecount(), tbFireSafetyHazardRecord.getMajorclass());
            hashMap.put("MC", name);
            hashMap.put("Address", "模拟系统A");
            hashMap.put("AlarmTime", tbFireSafetyHazardRecord.getTime());
            hashMap.put("Status", "已解决");
            hashMap.put("FireDuty", tbFireSafetyHazardRecord.getCharger());
            String phoneNumber = FireUtils.phoneDesensitization(tbFireSafetyHazardRecord.getContact());
            hashMap.put("FireDutyTel", phoneNumber);
            maps1.add(hashMap);
        }
        List<Map<String, Object>> maps2 = new ArrayList<>();
        for (TbFireResponseSpeed tbFireResponseSpeed : responseList) {
            Map<String, Object> hashMap = new HashMap<>();
            Date requiredfinishtime = tbFireResponseSpeed.getRequiredfinishtime();
            Date actualfinishtime = tbFireResponseSpeed.getActualfinishtime();
            if (actualfinishtime.after(requiredfinishtime)) {
                hashMap.put("MC", "未按照规定时间巡察");
                hashMap.put("Address", "模拟系统A");
                hashMap.put("TaskEndTime", FireUtils.dateTimeFormate(tbFireResponseSpeed.getActualfinishtime()));
                hashMap.put("TaskUserName", tbFireResponseSpeed.getHandler());
                hashMap.put("SignTime", "未解决");
                maps2.add(hashMap);
            }
        }
        map.put("staffList", maps1);
        map.put("processList", maps2);
        fireResponseVo.setData(map);
        fireResponseVo.setMethodName(FireMonitoringWarningConstant.GET_PROBLEMS);
        return fireResponseVo;
    }

    /**
     * 获取异常数据风险情况
     *
     * @return
     */
    @GetMapping("/getRiskOfAbnormal")
    @Override
    public ResponseVo getRiskOfAbnormal() {
        List<TbXfGenericPlanB> list = tbXfGenericPlanBServiceImpl.SelectXfGenericPlanB();

        Map<String, Integer> systemMap = new HashMap<>();
        systemMap.put("模拟系统A", 0);
        systemMap.put("模拟系统B", 0);

        // 计算 ycl（异常率）
        int abnormalItemCount = 0; // 异常字段数量
        int totalItemCount = list.size(); // 总字段数

        List<Map<String, Object>> ycList = new ArrayList<>();
        List<Map<String, Object>> wfgzdList = new ArrayList<>();

        int index = 1; // 行号从 1 开始
        for (TbXfGenericPlanB item : list) {
            if (item.getRequire() == null || item.getFinished() == null) {
                String systemName = "模拟系统B";
                systemMap.put(systemName, systemMap.get(systemName) + 1);
                abnormalItemCount++;

                // 构建异常记录
                Map<String, Object> ycRecord = new HashMap<>();
                ycRecord.put("TableName", systemName);
                ycRecord.put("ID", "require"); // 异常字段名
                ycRecord.put("rowid", index); //异常字段所在表的行数
                ycRecord.put("Field", "消防队伍预案表"); // 所在表名
                ycRecord.put("Remark", "要求预案编制数"); // 字段中文说明
                ycRecord.put("Title", "空值异常"); // 异常类型
                ycList.add(ycRecord);

                // 未覆盖验证机制字段记录
                Map<String, Object> wfgzdRecord = new HashMap<>();
                wfgzdRecord.put("TableName", systemName);
                wfgzdRecord.put("Field", "消防队伍预案表");
                wfgzdRecord.put("Remark", "要求预案编制数");
                wfgzdList.add(wfgzdRecord);
            }
            index++; // 每次循环自增
        }

        // 构建 chart 数据结构
        List<Map<String, Object>> chartData = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : systemMap.entrySet()) {
            Map<String, Object> chartEntry = new HashMap<>();
            chartEntry.put("systemName", entry.getKey());
            chartEntry.put("count", entry.getValue());
            chartData.add(chartEntry);
        }

        // 计算覆盖率（fgl）和异常率（ycl）
        double ycl = totalItemCount > 0 ? ((double) abnormalItemCount / totalItemCount) * 100 : 0.0;
        double fgl = 99.0;

        // 构建最终返回的数据结构
        Map<String, Object> data = new HashMap<>();
        data.put("chart", chartData); // 每个系统的异常数量
        data.put("ycList", ycList); // 异常记录列表
        data.put("ycl", ycl); // 异常率
        data.put("wfgzdList", wfgzdList); // 未覆盖验证字段
        data.put("fgl", fgl); // 覆盖率

        // 返回结果封装
        ResponseVo responseVo = new ResponseVo();
        responseVo.setData(data);
        responseVo.setMethodName("获取异常性风险数据");

        return responseVo;
    }


}
